package com.sunday.gateway.study.circuit.breaker;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.LocalDateTime;

@Slf4j
@Service
public class MyAnnotationService {

    /**
     * 注解方式 依赖于AOP能力
     * io.github.resilience4j.spring6.circuitbreaker.configure.CircuitBreakerAspect
     */
    @CircuitBreaker(name = "myExampleBreaker", fallbackMethod = "fallback")
    public Mono<String> process(long seconds) {
        log.info("Request received - processing a potentially time-consuming operation for {} seconds", seconds);
        Mono<String> delayedMono = Mono.delay(Duration.ofSeconds(seconds))
                .doOnNext(l -> log.info("Operation delayed by {} seconds complete", seconds))
                .then(Mono.just(STR."Delayed result - Operation took: \{seconds} seconds"))
                .timeout(Duration.ofSeconds(1));
        return delayedMono;
    }

    // Fallback method includes Throwable and other original method parameters
    public Mono<String> fallback(long seconds, Throwable throwable) {
        log.error("=================== seconds : {}", seconds);
        log.error("=================== Fallback triggered due to exception : ", throwable);
        return Mono.just(STR."Fallback at \{LocalDateTime.now()} - \{throwable.getMessage()}");
    }

}
